package net.qhzw.geologr5.gis.service.system.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.service.system.component.FileTemplate;
import net.qhzw.geologr5.gis.service.system.entity.ProjectType;
import net.qhzw.geologr5.gis.service.system.mapper.ProjectMapper;
import net.qhzw.geologr5.gis.service.system.mapper.ProjectTypeMapper;
import net.qhzw.geologr5.gis.service.system.query.ProjectTypeQuery;
import net.qhzw.geologr5.gis.service.system.service.ProjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ProjectTypeServiceImpl implements ProjectTypeService {

    @Autowired
    private ProjectTypeMapper projectTypeMapper;

    @Autowired
    private FileTemplate fileTemplate;

    @Autowired
    private ProjectMapper projectMapper;


    /***
     * 查询全部项目类别
     * @return
     */
    @Override
    public JsonResult findAll(ProjectTypeQuery query) {
        try {
            //项目类型数据
            List<ProjectType> projectTypeList = projectTypeMapper.selectprojectType(null);

            log.info("项目类别数据", JSON.toJSONString(projectTypeList));
            if (projectTypeList.isEmpty()) {
                return JsonResult.success("暂无数据");
            }
            List<ProjectType> projectTypes = projectTypeMapper.selectprojectType(query);
            //根节点
            List<ProjectType> rootNode = new ArrayList<>();
            for (ProjectType projectType : projectTypeList) {
                if (projectType.getPid() == 0) {
                    rootNode.add(projectType);
                }
            }
            //获取根节点下的所有子节点
            for (ProjectType projectType : rootNode) {
                List<ProjectType> child = getChild(projectType.getId(), projectTypes);
                projectType.setProjectTypeList(child);
            }
            log.info("rootNode: ==  {}", JSON.toJSONString(rootNode));
            return JsonResult.success(rootNode);
        } catch (Exception e) {
            log.error("查询全部项目类别失败==ProjectTypeServiceImpl==method:findAll==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 查询全部项目类别
     * @return
     */
    /*@Override
    public JsonResult findAll(ProjectTypeQuery query) {
        try {
            //项目类型数据
            List<ProjectType> projectTypeList = projectTypeMapper.selectList(null);
            log.info("项目类别数据", JSON.toJSONString(projectTypeList));
            if (projectTypeList.isEmpty()) {
                return JsonResult.success("暂无数据");
            }
            List<ProjectType> projectTypes = projectTypeMapper.selectprojectType(query);
            //根节点
            List<ProjectType> rootNode = new ArrayList<>();
            for (ProjectType projectType : projectTypeList) {
                if (projectType.getPid() == 0) {
                    rootNode.add(projectType);
                }
            }
            //获取根节点下的所有子节点
            for (ProjectType projectType : rootNode) {
                List<ProjectType> child = getChild(projectType.getId(), projectTypes);
                projectType.setProjectTypeList(child);
            }
            log.info("rootNode: ==  {}", JSON.toJSONString(rootNode));
            return JsonResult.success(rootNode);
        } catch (Exception e) {
            log.error("查询全部项目类别失败==ProjectTypeServiceImpl==method:findAll==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }
*/

    /***
     * 创建项目类别
     * @param projectType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult create(ProjectTypeQuery projectType) {
        log.info("创建项目类别==ProjectTypeServiceImpl==method:create==param: {}", JSON.toJSONString(projectType));
        try {
            if (projectType.getId() == null || projectType.getId() <= 0) {
                //新增
                if (projectType.getPid() == 0) {
                    ProjectType projectType1 = new ProjectType();
                    projectType1.setPid(projectType.getPid());
                    projectType1.setDataBase(projectType.getName());
                    projectTypeMapper.insert(projectType1);
                    return JsonResult.success();
                } else {
                    ProjectType projectType1 = projectTypeMapper.selectProjectTypeByid(projectType.getPid());
                    if (projectType1 == null) {
                        return JsonResult.error("项目类别不存在");
                    }
                    ProjectType projectType2 = new ProjectType();
                    projectType2.setPid(projectType.getPid());
                    projectType2.setDataBase(projectType.getName());
                    projectTypeMapper.insert(projectType2);
                    return JsonResult.success();
                }
            }
            //修改操作
            if (projectType.getId().equals(projectType.getPid())) {
                return JsonResult.error("数据不合法");
            }
            ProjectType projectType3 = new ProjectType();
            projectType3.setDataBase(projectType.getName());
            projectType3.setId(projectType.getId());
            projectType3.setPid(projectType.getPid());
            projectTypeMapper.updateById(projectType3);
            return JsonResult.success();
        } catch (Exception e) {
            log.info("创建项目类别失败==ProjectTypeServiceImpl==method:create==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 创建项目类别
     * @return
     */
     /*@Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult create(ProjectTypeQuery projectType) {
        log.info("创建项目类别==ProjectTypeServiceImpl==method:create==param: {}", JSON.toJSONString(projectType));
        try {
            Project project = projectMapper.selectProjectById(projectType.getProjectId());
            if (project == null){
                return JsonResult.error("项目不存在");
            }
            if (projectType.getId() != null && projectType.getId() > 0) {
                if (!StringUtils.isEmpty(projectType.getPid())) {
                    //修改操作
                    if (projectType.getPid().contains(String.valueOf(projectType.getId()))) {
                        return JsonResult.error("数据错误");
                    }
                    if (!"0".equals(projectType.getPid())) {
                        QueryWrapper<ProjectType> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("id", projectType.getPid());
                        List<ProjectType> projectTypeList = projectTypeMapper.selectList(queryWrapper);
                        if (projectTypeList.isEmpty()) {
                            return JsonResult.error("类型不存在");
                        }
                    }

                }
                ProjectType pt = new ProjectType();
                if (!StringUtils.isEmpty(projectType.getPid())) {
                    pt.setPid(Integer.valueOf(projectType.getPid()));
                }
                pt.setProjectId(projectType.getProjectId());
                pt.setId(projectType.getId());
                pt.setDataBase(projectType.getName());
                if (pt.getPid().equals(pt.getId())) {
                    return JsonResult.error("数据错误");
                }
                int count = projectTypeMapper.updateById(pt);
                System.out.println("count; " + count);
                return JsonResult.success("修改成功");
            }
            //新增
            if (projectType.getPid().equals(projectType.getId())) {
                return JsonResult.error("数据错误");
            }
            if ("0".equals(projectType.getPid())) {
                ProjectType pt = new ProjectType();
                pt.setPid(0);
                pt.setProjectId(projectType.getProjectId());
                pt.setDataBase(projectType.getName());
                pt.setLeve(1);
                projectTypeMapper.insert(pt);
                return JsonResult.success();
            }
            QueryWrapper<ProjectType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", projectType.getPid());
            List<ProjectType> projectTypeList = projectTypeMapper.selectList(queryWrapper);
            if (projectTypeList.isEmpty()) {
                return JsonResult.error("类型不存在");
            }
            ProjectType pt = new ProjectType();
            if (!StringUtils.isEmpty(projectType.getPid())) {
                pt.setPid(Integer.valueOf(projectType.getPid()));
            }
            pt.setProjectId(projectType.getProjectId());
            pt.setDataBase(projectType.getName());
            projectTypeMapper.insert(pt);
            return JsonResult.success();
        } catch (Exception e) {
            log.info("创建项目类别失败==ProjectTypeServiceImpl==method:create==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }*/


    /***
     * 删除项目类别
     * @param id
     * @return
     */
    @Override
    @Transactional
    public JsonResult delete(Integer id) {
        try {
            List<Integer> idList = new ArrayList<>();
            ProjectType projectType = projectTypeMapper.selectById(id);
            List<ProjectType> all = projectTypeMapper.findAll();
            List<Integer> pidList = getPidList(projectType.getId(), all);
            List<Integer> idList1 = getIdList(pidList, all);
            idList.add(id);
            idList.addAll(pidList);
            idList.addAll(idList1);
            int count = projectTypeMapper.deleteBatchIds(idList);
            if (count > 0) {
                return JsonResult.success("删除成功");
            }
            return JsonResult.error("删除失败");
        } catch (Exception e) {
            log.info("删除项目类别失败==ProjectTypeServiceImpl==method:delete==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }


    }


    /***
     * 获取子级id
     * @param ids
     * @param all
     * @return
     */
    private List<Integer> getIdList(List<Integer> ids, List<ProjectType> all) {
        List<Integer> list = new ArrayList<>();
        if (ids.isEmpty()) {
            return list;
        }
        for (Integer id : ids) {
            List<Integer> pidList = getPidList(id, all);
            list.addAll(pidList);
        }
        List<Integer> pidList = getIdList(list, all);
        list.addAll(pidList);
        return list;
    }

    /***
     * 根据id获取pid
     * @param id
     * @param all
     * @return
     */
    private List<Integer> getPidList(Integer id, List<ProjectType> all) {
        log.info("pid{}: , all:{} ", id, JSON.toJSONString(all));
        List<Integer> idList = new ArrayList<>();
        for (ProjectType projectType : all) {
            if (id.equals(projectType.getPid())) {
                idList.add(projectType.getId());
            }
        }
        return idList;
    }


    /***
     * 查询编号下拉框
     * @return
     */
    @Override
    public JsonResult getProjectType(Map<String, String> param) {
        try {
            String queryFlag = param.get("queryFlag");
            List<Map<String, String>> maps = projectTypeMapper.selectCodeBox(queryFlag);
            return JsonResult.success(maps);
        } catch (Exception e) {
            return JsonResult.error();
        }
    }


    /***
     * 上传文件
     * @param targetPath
     * @param file
     */
    private String upload(String targetPath, MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename(); //获取文件名，带后缀
        File folderPath = new File(targetPath);
        //查询文件夹是否存在
        if (!folderPath.exists() && !folderPath.isDirectory()) {
            folderPath.mkdirs();
            log.info("目录不存在，创建新文件夹");
        }
        File filePath = new File(folderPath + filename);
        log.info("上传的文件url:{}", filePath);
        //将上传的文件写到服务器上指定的文件路径
        file.transferTo(filePath);
        return filePath.getPath();
    }


    /***
     * 获取所有的子节点
     * @param id 父id
     * @param projectTypes 匹配数据
     * @return
     */
    private List<ProjectType> getChild(Integer id, List<ProjectType> projectTypes) {
        //子节点
        List<ProjectType> childList = new ArrayList<>();
        for (ProjectType projectType : projectTypes) {
            if (id.equals(projectType.getPid())) {
                childList.add(projectType);
            }
        }
        for (ProjectType projectType : childList) {
            List<ProjectType> child = getChild(projectType.getId(), projectTypes);
            projectType.setProjectTypeList(child);
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<ProjectType>();
        }
        return childList;
    }
}
